﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Threading;
using TableToExcel;
using ExcelToTable;
using System.IO;
using AlanUtilities;
using DBAccessor.Accessor;
using DBList.Entities;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO.Compression;
using System.Text.RegularExpressions;
using System.Web;
using System.Collections;

namespace WebnetUploadApp
{
    public partial class ZDHWebnetApp : Form
    {
		public static Double	st_progress = 0;
		public static bool		st_bCanCloseApp = true;
		System.Windows.Forms.Timer	m_myTimer;
        public ZDHWebnetApp()
        {
            InitializeComponent();
			m_myTimer = null;
		}

        private void WebnetApp_Load(object sender, EventArgs e)
        {
			progressBar1.Visible = false;
			this.tabControl.SelectedIndex = 1;
		}

		private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
		{
			Double dCurProgress = st_progress;
			if (dCurProgress > 100 || dCurProgress < 0)
			{
				this.Cursor = Cursors.Arrow;

				m_myTimer.Stop();
				m_myTimer.Dispose();
				m_myTimer = null;

				st_bCanCloseApp = true;
				button1.Enabled = true;
				btnUpload.Enabled = true;
				tabControl.Enabled = true;

				progressBar1.Visible = false;
				if (dCurProgress > 100)
				{
					textBoxKind.Text = "";
					tbKindCode.Text = "";
					tbBeginInt.Text = "";
					tbEndInt.Text = "";
					tbKindPrice.Text = "";
					tbKindContent.Text = "";
					tbSrcXlsFile.Text = "";
				}
			}
			else {
				progressBar1.Visible = true;
				progressBar1.Maximum = 100;
				progressBar1.Minimum = 1;
				int nValue = (int)Math.Ceiling(dCurProgress);
				if (nValue < 1) nValue = 1;
				else if (nValue > 100) nValue = 100;
				progressBar1.Value = (int)Math.Ceiling(dCurProgress);
			}
		}
        //根据DataTable 生成Excel文件(第一行为标题). 具体你可以自己再改改.
        //注意： 以下代码需要 Excel.dll的支持（网上搜下就有得下的）
        /// <summary>
        /// 根据DataTable内容生成相应的Excel文件.
        /// </summary>
        /// <param name="filename">生成Excel的文件名.</param>
        /// <param name="dt">生成Excel所对应的数据表.</param>
        static void CreateXls(string filename, DataTable dt)
        {
            if (filename != string.Empty)
            {
                Excel.ApplicationClass xlApp = new Excel.ApplicationClass();
                Excel.WorkbookClass wb = (Excel.WorkbookClass)xlApp.Workbooks.Add(System.Reflection.Missing.Value);
                for (int k = 1; k <= dt.Columns.Count; k++)
                {
                    xlApp.Cells[1, k] = dt.Columns[k - 1].ColumnName;
                }
                for (int i = 1; i <= dt.Rows.Count; i++)
                {
                    for (int j = 1; j <= dt.Columns.Count; j++)
                    {
                        xlApp.Cells[i + 1, j] = dt.Rows[i - 1][j - 1];
                    }
                }
                wb.Saved = true;
                xlApp.ActiveWorkbook.SaveCopyAs(filename);
                xlApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject((object)xlApp);
            }
        }
		static void DoWork(Object state)
		{
			try
			{
				DataTable dt = new DataTable();
				dt.Columns.Add(@"BarCode");
				dt.Columns.Add(@"Password");
				dt.Columns.Add(@"Kind");
				dt.Columns.Add(@"KindCode");
                dt.Columns.Add(@"Price");

				MyParameters theParams = (MyParameters)state;
				ZDHWebnetApp.st_progress = 1;

				Dictionary<string, int> pwdDict = new Dictionary<string, int>();
				string strCurDir = Environment.CurrentDirectory;
				strCurDir += "\\";
				string strpwdFile = strCurDir + theParams.Year.ToString();
				strpwdFile += @"ImpTemplate.bob";
				if (File.Exists(strpwdFile))
				{
					pwdDict = OperateFiles.ReadPWDFromFile(strpwdFile);
				}

				Random random = new Random();
				Double ftt = theParams.EndInt - theParams.StartInt + 1;
				ftt = 98.0 / ftt;
				string strTM, strPWD;
				for (int it = theParams.StartInt; it <= theParams.EndInt; it++)
				{
					strTM = theParams.Year.ToString().Remove(0, 2);
					strTM += theParams.KindCode;
					string strNumber = it.ToString();
					while (strNumber.Length < 7)
					{
						strNumber = "0" + strNumber;
					}
					strTM += strNumber;
					do
					{
						strPWD = string.Empty;
						for (int i = 0; i < 6; i++)
						{
							int number = random.Next();
							number = number % 9;
							strPWD += number.ToString();
						}
					} while (pwdDict.ContainsKey(strPWD));

					DataRow dr = dt.NewRow();
					dr[0] = strTM;
					dr[1] = strPWD;
					dr[2] = theParams.Kind;
					dr[3] = theParams.KindCode;
                    dr[4] = theParams.Price.ToString();
					dt.Rows.Add(dr);
					pwdDict.Add(strPWD, 1);

					ZDHWebnetApp.st_progress += ftt;
				}
				ftt = dt.Rows.Count;

				string strXls = theParams.XLSDir;
				strXls += "\\";
				string strFile = DateTime.Now.ToString("yyyyMMddHHmmss");
				strFile += theParams.Kind;
				strFile += "-";
				strFile += theParams.StartInt.ToString();
				strFile += "-";
				strFile += theParams.EndInt.ToString();
				strXls += strFile;
				Table_ToExcel tte = new Table_ToExcel();
				tte.u_DataTableToExcel2(dt, strXls, 10000, "2003");

				ZDHWebnetApp.st_progress = 100;
				OperateFiles.SavePWD2File(strpwdFile, pwdDict);
				ZDHWebnetApp.st_progress = 101;
			}
			catch (System.Exception e)
			{
				MessageBox.Show(e.Message);
				ZDHWebnetApp.st_progress = -101;
			}
			finally
			{
			}
		}
        private void button1_Click(object sender, EventArgs e)
        {
			String fdir = saveXlsDir.Text;
			if(fdir.Length == 0){
				fdir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
			}
			DateTime dt = DateTime.Now;
			int nYear = dt.Year;
			string  strInt = combYear.Text;
			if (strInt.Length == 0)
			{
				MessageBox.Show(@"请选择年份！");
				return;
			}
			int.TryParse(strInt, out nYear);
			MyParameters theParam = new MyParameters();
			theParam.Year = nYear;
			theParam.Kind = textBoxKind.Text.Trim();
			theParam.KindCode = tbKindCode.Text.Trim();
			strInt = tbBeginInt.Text.Trim();
			if (strInt.Length == 0){
				MessageBox.Show(@"请输入开始数值！");
				return;
			}
			int sval = 0, eval = 0;
			int.TryParse(strInt, out sval);
			strInt = tbEndInt.Text.Trim();
			if (strInt.Length == 0)
			{
				MessageBox.Show(@"请输入结束数值！");
				return;
			}
			int.TryParse(strInt, out eval);
			theParam.StartInt = sval;
			theParam.EndInt = eval;
			if (theParam.Kind.Length == 0 || theParam.KindCode.Length == 0){
				MessageBox.Show(@"请输入品种和代码！");
				return;
			}
			theParam.XLSDir = fdir;
            Decimal dPrice = 0;
            if (tbKindPrice.Text.Trim().Length == 0){
                MessageBox.Show(@"请输入价格！");
                return;
            }
            Decimal.TryParse(tbKindPrice.Text.Trim(), out dPrice);
            theParam.Price = dPrice;
            theParam.KindContent = tbKindContent.Text;

			ZDHWebnetApp.st_progress = 0.0f;
			st_bCanCloseApp = false;
			bool result = ThreadPool.QueueUserWorkItem(DoWork, theParam);
			if (!result)
				st_bCanCloseApp = true;
			else {
				tabControl.Enabled = false;
				button1.Enabled = false;
				this.Cursor = Cursors.WaitCursor;
				m_myTimer = new System.Windows.Forms.Timer();
				m_myTimer.Tick += new EventHandler(TimerEventProcessor);
				m_myTimer.Interval = 200;
				m_myTimer.Start();
			}
        }

		private void selSrcFile_Click(object sender, EventArgs e)
		{
			if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
			{
				String fdir = folderBrowserDialog1.SelectedPath;
				saveXlsDir.Text = fdir;
			}
		}
		private void ZDHWebnetApp_FormClosing(object sender, FormClosingEventArgs e)
		{
			if(!st_bCanCloseApp){
				MessageBox.Show(@"不能关闭，稍后再试！");
				e.Cancel = true;
			} else {
				e.Cancel = false;
			}
		}
		private static byte[] BuildUserNameStream(String struser, String strpwd)
		{
			byte[] pRet = null;
			byte[] pIndex = new byte[3];
			if (pIndex != null)
			{
				pIndex[0] = (Byte)2;
				Array rsutArray = Array.CreateInstance(typeof(Byte), 2 * 255);
				int nTotalLen = 0;

				string strEnc = OperateControl.StringEncrypt(struser);
				byte[] arEnc = Encoding.UTF8.GetBytes(strEnc);
				Array.Copy(arEnc, 0, rsutArray, nTotalLen, arEnc.Length);
				nTotalLen += arEnc.Length;
				pIndex[1] = (Byte)arEnc.Length;

				strEnc = OperateControl.StringEncrypt(strpwd);
				arEnc = Encoding.UTF8.GetBytes(strEnc);
				Array.Copy(arEnc, 0, rsutArray, nTotalLen, arEnc.Length);
				nTotalLen += arEnc.Length;
				pIndex[2] = (Byte)arEnc.Length;

				pRet = new Byte[3 + nTotalLen];
				if (pRet != null)
				{
					Array.Copy(pIndex, 0, pRet, 0, 3);
					Array.Copy(rsutArray, 0, pRet, 3, nTotalLen);
				}
			}
			return pRet;
		}
		private static byte[] BuildRequestStream(DataTable dt, int sint, int nCount)
		{
			byte[]	pRet = null;
			int eint = sint + nCount;
			if (eint > dt.Rows.Count)
				nCount = dt.Rows.Count - sint;
			if (nCount > 0 && nCount < 220){
				byte[] pIndex = new byte[nCount + 1];
				if(pIndex != null){
					pIndex[0] = (Byte)nCount;
					Array rsutArray = Array.CreateInstance(typeof(Byte), nCount*255);
					int nTotalLen = 0;
					for(int i = 0; i < nCount; i++)
					{
						eint = sint + i;

						DataRow dr = dt.Rows[eint];
						string str = dr[@"BarCode"].ToString().Trim();
						str += "#";
						str += dr[@"Password"].ToString().Trim();
						str += "#";
						str += dr[@"Kind"].ToString().Trim();
						str += "#";
						str += dr[@"KindCode"].ToString().Trim();
						str += "#";
						str += dr[@"Price"].ToString().Trim();

						string strEnc = OperateControl.StringEncrypt(str);
						byte[] arEnc = Encoding.UTF8.GetBytes(strEnc);
						Array.Copy(arEnc, 0, rsutArray, nTotalLen, arEnc.Length);
						nTotalLen += arEnc.Length;
						pIndex[i+1] = (Byte)arEnc.Length;
					}
					pRet = new Byte[nCount + 1 + nTotalLen];
					if(pRet != null){
						Array.Copy(pIndex, 0, pRet, 0, nCount + 1);
						Array.Copy(rsutArray, 0, pRet, nCount + 1, nTotalLen);
					}
				}
			}
			return pRet;
		}

		private void button2_Click(object sender, EventArgs e)
		{
			openFileDialog1.Multiselect = false;
			if (openFileDialog1.ShowDialog() == DialogResult.OK)
			{
				String fName = openFileDialog1.FileName;
				tbSrcXlsFile.Text = fName;
			}
		}

		private void btnUpload_Click(object sender, EventArgs e)
		{
			String fdir = tbSrcXlsFile.Text;
			if (fdir.Length == 0){
				MessageBox.Show(@"请选择XLS文件！");
				return;
			}
			String strUser, strpwd;
			strUser = tbUserName.Text.Trim();
			strpwd = tbPassword.Text.Trim();
			if (strUser.Length == 0 || strpwd.Length == 0)
			{
				MessageBox.Show(@"登录名和密码不能为空！");
				return;
			}
			if(tbUploadSite.Text.Trim().Length == 0){
				MessageBox.Show(@"上传网址不能为空！");
				return;
			}
			MyUploadParams myParams = new MyUploadParams();
			myParams.XLSFile = fdir;
			myParams.UserName = strUser;
			myParams.PWD = strpwd;
			myParams.UploadSite = tbUploadSite.Text.Trim();
			if (myParams.UploadSite.StartsWith("www")){
				myParams.UploadSite = @"http://" + myParams.UploadSite;
			}
			int nLen = myParams.UploadSite.Length;
			char lastestChar = myParams.UploadSite[nLen - 1];
			if (lastestChar != '/')
				myParams.UploadSite += '/';
			myParams.HasRandom = chkboxRandom.Checked;

			ZDHWebnetApp.st_progress = 0.0f;
			st_bCanCloseApp = false;
			bool result = ThreadPool.QueueUserWorkItem(DoUpload, myParams);
			if (!result)
				st_bCanCloseApp = true;
			else
			{
				tabControl.Enabled = false;
				btnUpload.Enabled = false;
				this.Cursor = Cursors.WaitCursor;
				m_myTimer = new System.Windows.Forms.Timer();
				m_myTimer.Tick += new EventHandler(TimerEventProcessor);
				m_myTimer.Interval = 200;
				m_myTimer.Start();
			}
		}
		private static void BugFix_CookieDomain(CookieContainer cookieContainer)
		{
			System.Type _ContainerType = typeof(CookieContainer);
			Hashtable table = (Hashtable)_ContainerType.InvokeMember("m_domainTable",
									   System.Reflection.BindingFlags.NonPublic |
									   System.Reflection.BindingFlags.GetField |
									   System.Reflection.BindingFlags.Instance,
									   null,
									   cookieContainer,
									   new object[] { });
			ArrayList keys = new ArrayList(table.Keys);
			foreach (string keyObj in keys)
			{
				string key = (keyObj as string);
				if (key[0] == '.')
				{
					string newKey = key.Remove(0, 1);
					table[newKey] = table[keyObj];
				}
			}
		}
		static void DoUpload(Object state)
		{
			CookieContainer theCC = new CookieContainer();
			try
			{
				MyUploadParams myParams = (MyUploadParams)state;
				String strXlsFile = myParams.XLSFile;
				ZDHWebnetApp.st_progress = 1;
				Excel_ToTable	ett = new Excel_ToTable();
				DataTable dt = ett.CreateDataFromExcel(strXlsFile);

				String strAbcURL = myParams.UploadSite;
				strAbcURL += @"AddBarCode.aspx";
				String	strToken = "";
				ZDHWebnetApp.st_progress = 2;
				int	 nTimeOut = 30000;
				Cookie myCookie = new Cookie("uploadmode", "11");
				CookieCollection cokcol = new CookieCollection();
				cokcol.Add(myCookie);
				Uri absoluteUri = new Uri(strAbcURL);
				theCC.Add(absoluteUri, cokcol);
				byte[] steamData = BuildUserNameStream(myParams.UserName, myParams.PWD);
				//BugFix_CookieDomain(theCC);
				String strurl = strAbcURL + @"?action=1";
				HttpWebResponse webResp = HttpWebResponseUtility.CreatePostHttpResponse(strurl, nTimeOut, null, theCC, steamData);
				if(webResp == null){
					System.Exception exp = new Exception(@"登入失败！");
					throw exp;
				}
				else {
					myCookie = webResp.Cookies["uploadflag"];
					strToken = myCookie.Value;
					String strResult = webResp.Cookies["DoResult"].Value;
					if (strResult != @"success"){
						throw new Exception(strResult);
					}
					webResp.Close();
				}
				Double ftt = dt.Rows.Count;
				ftt = 98.0 / ftt;
				int i, ist, nStrip = 200, nNum = (dt.Rows.Count + nStrip-1)/nStrip;
				for(ist = i = 0; i < nNum; i++, ist += 200){
					if(i+1 == nNum){
						nStrip = dt.Rows.Count - ist;
					}
					steamData = BuildRequestStream(dt, ist, nStrip);
					if(steamData != null){
						strToken = OperateControl.StringEncrypt(strToken);
						strToken = HttpUtility.UrlEncode(strToken, Encoding.UTF8);
						myCookie.Value = strToken;
						cokcol.Add(myCookie);
						theCC.Add(cokcol);
						strurl = strAbcURL + @"?action=2";
						if (myParams.HasRandom)
							strurl += @"&nonerandom=0";
						else
							strurl += @"&nonerandom=111";
						webResp = HttpWebResponseUtility.CreatePostHttpResponse(strurl, nTimeOut, null, theCC, steamData);
						if (webResp == null)
						{
							System.Exception exp = new Exception(@"错误！请稍后重试！");
							throw exp;
						}
						else
						{
							myCookie = webResp.Cookies["uploadflag"];
							strToken = myCookie.Value;
							String strResult = webResp.Cookies["DoResult"].Value;
							if (strResult != @"success"){
								throw new Exception(strResult);
							}
							webResp.Close();
						}
					} else {
						System.Exception exp = new Exception(@"错误！请稍后重试！");
						throw exp;
					}
					ZDHWebnetApp.st_progress += (ftt * nStrip);
				}
				ZDHWebnetApp.st_progress = 101;
			}
			catch (System.Exception e)
			{
				MessageBox.Show(e.Message);
				ZDHWebnetApp.st_progress = -101;
			}
			finally
			{
			}
		}
    }
	public class MyUploadParams{
		private string _xlsfile;
		private string _username;
		private string _pwd;
		private string _url;
		private bool _bhasRandom;

		public string XLSFile
		{
			set { _xlsfile = value; }
			get { return _xlsfile; }
		}
		public string UserName
		{
			set { _username = value; }
			get { return _username; }
		}
		public string PWD
		{
			set { _pwd = value; }
			get { return _pwd; }
		}
		public String UploadSite
		{
			set { _url = value; }
			get { return _url; }
		}
		public bool HasRandom
		{
			set { _bhasRandom = value; }
			get { return _bhasRandom; }
		}
	}
	public class MyParameters
	{
		private int _year;
		private string _kind;
		private string _kindcode;
		private int _sint;
		private int _eint;
		private string _xlsDir;
        private Decimal _price;
        private string _kindcontent;

		public int Year
		{
			set { _year = value; }
			get { return _year; }
		}
		public string Kind
		{
			set { _kind = value; }
			get { return _kind; }
		}
		public string KindCode
		{
			set { _kindcode = value; }
			get { return _kindcode; }
		}
		public int StartInt
		{
			set { _sint = value; }
			get { return _sint; }
		}
		public int EndInt
		{
			set { _eint = value; }
			get { return _eint; }
		}
		public string XLSDir{
			set { _xlsDir = value; }
			get { return _xlsDir; }
		}
        public Decimal Price
        {
            set { _price = value; }
            get { return _price; }
        }
        public string KindContent
        {
            set { _kindcontent = value; }
            get { return _kindcontent; }
        }
    }
}
